package config.java;

import java.util.Hashtable;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
 * xml解析
 * @author liao
 *
 */
public class SAXHandler extends DefaultHandler {

	private Hashtable<String, String> value = new Hashtable<String, String>();

	private boolean isRoot = true;
	private boolean isValid = false;
	private int tmpIndex = 0;
	
	private String currentKey = null;

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		try {
			if (!isRoot) {
				char[] bt = new char[length];
				System.arraycopy(ch, start, bt, 0, length);
				String str = new String(bt);
				//System.out.println(str);
				if(isValid){
					value.put(currentKey, str);
				}
			}
		} catch (Exception ex) {
			ConfigLog.errorLog(ex);
		}
	}

	public void startElement(String uri, String localName, String qName,
			Attributes attr) throws SAXException {
		tmpIndex++;
		// 跳过根节点，只能有一个根节点
		if (tmpIndex > 1) {
			isRoot = false;
			currentKey = qName;
			isValid = true;
		}
	}

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		isValid = false;
	}

	public void endDocument() throws SAXException {

	}

	public void startDocument() throws SAXException {

	}

	public Hashtable<String, String> getValue() {
		return value;
	}

//	public static void main(String[] args) {
//		try {
//			SAXHandler handler = new SAXHandler();
//			SAXParserFactory saxparserfactory = SAXParserFactory.newInstance();
//			SAXParser saxparser = saxparserfactory.newSAXParser();
//			saxparser.parse(new File("g:\\test\\x1.xml"), handler);
//			Hashtable<String,String> h = handler.getValue();
//			System.out.println(h.get("name"));
//		} catch (Exception ex) {
//			ex.printStackTrace();
//		}
//	}

}
